<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 自定义组件，标题 -->
      <PageTitle :show-before="true">
        <template v-slot:before>
          <h2>职位管理</h2>
        </template>
      </PageTitle>
      <el-row type="flex" style="margin-top: 20px">
        <el-col :span="16">
          <el-row :gutter="10">
            <el-col :span="4">
              <el-select
                v-model="jobLists.audit"
                placeholder="不限审核状态"
                clearable
                @change="handleSelectAuditChange"
              >
                <el-option
                  v-for="item in auditStatus"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select
                placeholder="不限招聘状态"
                v-model="jobLists.display"
                clearable
                @change="handleSelectStatusChange"
              >
                <el-option
                  v-for="item in hireStatus"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select
                v-model="jobLists.sort"
                placeholder="按添加时间排序"
                clearable
                @change="handleSortChange"
              >
                <el-option
                  v-for="item in addTimeSort"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="8">
          <el-row type="flex" :gutter="10">
            <el-select
              v-model="jobLists.keyType"
              placeholder="职位名称"
              clearable
            >
              <el-option
                v-for="item in positionName"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              >
              </el-option>
            </el-select>

            <el-row type="flex" :gutter="10">
              <el-input
                v-model="jobLists.keyword"
                placeholder="请输入搜索内容"
                @keyup.enter.native="searchClick"
              ></el-input>
              <el-button type="primary" @click="searchClick">
                <i class="el-icon-search"></i>
              </el-button>
            </el-row>
          </el-row>
        </el-col>
      </el-row>
      <!-- 数据表 -->
      <el-table
        v-loading="downloadLoading"
        ooltip-effect="dark"
        :data="jobListArray"
        max-height="600px"
        style="margin-top: 20px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          label="职位名称"
          align="center"
          width="width"
          prop="companyName"
          fixed
        >
          <template slot-scope="scope">
            <div>
              <el-link type="primary" @click="jobClick(scope.row)">
                <!-- <el-link :href="scope.row.jobLink" type="primary">{{
                scope.row.jobname
              }}</el-link> -->
                {{ scope.row.jobname }}
              </el-link>
            </div>
            <div>
              <el-link type="primary" @click="companyClick(scope.row)">
                <!-- <el-link :href="scope.row.companyLink">{{
                scope.row.companyName
              }}</el-link> -->
                {{ scope.row.companyName }}
              </el-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="会员/职位手机号"
          align="center"
          prop="memberMobile"
          fixed
        >
          <template slot-scope="scope">
            <div>
              <i class="el-icon-user"></i>
              {{ scope.row.memberMobile }}
            </div>
            <div>
              <i class="el-icon-document"></i>
              {{ scope.row.mobile }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="审核状态"
          align="center"
          prop="user_status"
          width="130"
          fixed
        >
          <template slot-scope="scope">
            <el-tag type="warning" v-if="scope.row.audit === 0">待审核</el-tag>
            <el-tag type="success" v-if="scope.row.audit === 1">已通过</el-tag>
            <el-tag type="danger" v-if="scope.row.audit === 2">未通过</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="创建/刷新时间"
          align="center"
          prop="refreshtime"
          width="180"
        >
          <template slot-scope="scope">
            <div>
              <i class="el-icon-time"></i>
              {{ scope.row.addtime | dateFormat }}
            </div>
            <div>
              <i class="el-icon-time"></i>
              {{ scope.row.updatetime | dateFormat }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="职位状态" align="center" prop="qualification">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.display"
              @change="switchChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          prop="com_name"
          width="300"
        >
          <template slot-scope="scope">
            <!-- <el-button
              type="primary"
              size="small"
              @click="manageClick(scope.row.uid)"
              >管理</el-button
            > -->
            <el-button
              type="warning"
              size="small"
              @click="examineClick(scope.row.id)"
              >审核</el-button
            >
            <!-- <el-button type="primary" size="small" @click="editBtn(scope.row)"
              >编辑</el-button
            > -->
            <el-button type="danger" size="small" @click="delBtn(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-row :gutter="10" style="margin-top: 10px" type="flex" justify="end">
        <el-col :span="8">
          <!-- <el-button type="primary" size="small" @click="refreshClick"
            >刷新</el-button
          > -->
          <el-button type="warning" size="small" @click="examinePlClick"
            >批量审核</el-button
          >
          <el-button type="danger" size="small" @click="delBtnClick"
            >批量删除</el-button
          >
        </el-col>
        <el-col :span="16">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            style="text-align: right"
          >
          </el-pagination>
        </el-col>
      </el-row>

      <!-- 批量审核状态 -->
      <el-dialog
        title="将所选职位设置为"
        :visible.sync="examineDialog"
        width="30%"
      >
        <el-form ref="form" label-width="80px">
          <el-form-item label="审核状态:">
            <!-- 添加 v-if 确保有选中数据时才渲染 -->
            <el-radio-group
              v-if="selectedRows.length > 0"
              v-model="selectedRows[0].audit"
            >
              <el-radio :label="0">待审核</el-radio>
              <el-radio :label="1">已通过</el-radio>
              <el-radio :label="2">未通过</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="selectedRows.length > 0 && selectedRows[0].audit == 2"
            label="原因:"
          >
            <el-input
              v-model="selectedRows[0].reason"
              type="textarea"
              :rows="3"
              maxlength="30"
              show-word-limit
              placeholder="请填写不通过原因"
            >
            </el-input>
          </el-form-item>
          <!-- <el-form-item label="">
            <el-row :gutter="10" type="flex" justify="end">
              <el-button size="mini" @click="examineDialog = false"
                >取消</el-button
              >
              <el-button type="primary" size="mini" @click="auditClick"
                >确定</el-button
              >
            </el-row>
          </el-form-item> -->
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="examineDialog = false">取 消</el-button>
          <el-button type="primary" @click="auditClick">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog
        title="将所选职位设置为"
        :visible.sync="examineOneDialog"
        width="30%"
      >
        <el-form ref="form" label-width="80px">
          <el-form-item label="审核状态:">
            <!-- 添加 v-if 确保有选中数据时才渲染 -->
            <el-radio-group v-model="auditQuery[0].audit">
              <el-radio :label="0">待审核</el-radio>
              <el-radio :label="1">已通过</el-radio>
              <el-radio :label="2">未通过</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="auditQuery[0].audit == 2" label="原因:">
            <el-input
              v-model="auditQuery[0].reason"
              type="textarea"
              :rows="3"
              maxlength="30"
              show-word-limit
              placeholder="请填写不通过原因"
            >
            </el-input>
          </el-form-item>
          <!-- <el-form-item label="">
            <el-row :gutter="10" type="flex" justify="end">
              <el-button @click="examineOneDialog = false">取消</el-button>
              <el-button type="primary" @click="auditOneClick">确定</el-button>
            </el-row>
          </el-form-item> -->
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="examineOneDialog = false">取消</el-button>
          <el-button type="primary" @click="auditOneClick">确定</el-button>
        </span>
      </el-dialog>

      <!-- 职位名称弹框 -->
      <el-dialog title="职位详情" width="width" :visible.sync="jobNameDialog">
        <el-form :model="formData" label-width="120px" disabled>
          <el-form-item label="职位名称">
            <el-input v-model="formData.jobname"></el-input>
          </el-form-item>
          <el-form-item label="职位性质">
            <el-input v-model="formData.natureText" disabled></el-input>
          </el-form-item>
          <el-form-item label="薪资分布">
            <el-input v-model="formData.wageText" disabled></el-input>
          </el-form-item>

          <el-form-item label="公司名称">
            <el-input v-model="formData.companyName" disabled></el-input>
          </el-form-item>

          <el-form-item label="学历要求">
            <el-input v-model="formData.educationText" disabled></el-input>
          </el-form-item>
          <el-form-item label="工作经验">
            <el-input v-model="formData.experienceText" disabled></el-input>
          </el-form-item>

          <el-form-item label="工作地区">
            <div
              style="
                background-color: #f5f7fa;
                color: #c0c4cc;
                border-color: #e4e7ed;
                padding: 0px 15px;
              "
            >
              {{
                getDistrictText(
                  formData.district1,
                  formData.district2,
                  formData.district3
                )
              }}
            </div>
          </el-form-item>

          <el-form-item label="工作地址">
            <el-input v-model="formData.address" disabled></el-input>
          </el-form-item>

          <el-form-item label="职位亮点">
            <div class="tags-container">
              <el-tag
                v-for="(tag, index) in formData.tags"
                :key="index"
                size="small"
                style="margin-right: 5px; margin-bottom: 5px"
              >
                {{ tag }}
              </el-tag>
            </div>
          </el-form-item>
          <el-form-item label="职位描述">
            <el-input
              type="textarea"
              :rows="5"
              v-model="formData.content"
              placeholder=""
              disabled
            ></el-input>
          </el-form-item>
        </el-form>

        <div slot="footer">
          <el-button @click="jobNameDialog = false">关 闭</el-button>
        </div>
      </el-dialog>

      <!-- 公司名称 -->
      <el-dialog
        title="公司详情"
        width="width"
        :visible.sync="companyNameDialog"
      >
        <el-form :model="companyNames" label-width="120px">
          <el-form-item label="公司名称">
            <el-input v-model="companyNames.sitename" disabled></el-input>
          </el-form-item>
          <el-form-item label="在招职位">
            <el-input
              v-model="companyNames.companyJobCount"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="简历查看率">
            <el-input v-model="companyNames.companyLook" disabled></el-input>
          </el-form-item>
          <el-form-item label="公司地址">
            <el-input
              v-model="companyNames.companyAddress"
              placeholder=""
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="公司类别">
            <el-input
              v-model="companyNames.companyTradeText"
              placeholder=""
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="公司性质">
            <el-input
              v-model="companyNames.companyNatureText"
              placeholder=""
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="企业福利">
            <div class="tags-container">
              <el-tag
                v-for="(tag, index) in companyNames.companyTagTextArr"
                :key="index"
                size="small"
                style="margin-right: 5px; margin-bottom: 5px"
              >
                {{ tag }}
              </el-tag>
            </div>
          </el-form-item>
          <el-form-item label="公司简介">
            <el-input
              disabled
              type="textarea"
              :rows="5"
              v-model="companyNames.companyContent"
              placeholder=""
            ></el-input>
          </el-form-item>
        </el-form>

        <div slot="footer">
          <el-button @click="companyNameDialog = false">关 闭</el-button>
        </div>
      </el-dialog>
      <!-- <examine ref="examineRef" :examineDialog.sync="examineDialog" /> -->
      <allExamine :allExamineDialog.sync="allExamineDialog" />
    </div>
  </div>
</template>

<script>
// import examine from "@/views/user/positionInfo/positionManage/components/examine";
import allExamine from "@/views/user/positionInfo/positionManage/components/allExamine";
import {
  jobListApi,
  updateDisplayByIdApi,
  delPositionByIdApi,
  updateAuditByIdAuditApi,
  selTokenByUIdApi,
  updateAuditApi,
  delPositionByIdsApi,
  selCategoryJobListApi,
  selCategoryDistrictListApi,
} from "@/api/client";
import company from "@/router/modules/company";
export default {
  components: {
    // examine,
    allExamine,
  },
  computed: {
    formData() {
      const natureMap = {
        1: "全职",
        2: "实习",
        3: "兼职",
      };

      return {
        jobname: this.jobListName[0]?.jobname || "--",
        wageText: this.jobListName[0]?.wageText || "--",
        companyName: this.jobListName[0]?.companyName || "--",
        educationText: this.jobListName[0]?.educationText || "--",
        experienceText: this.jobListName[0]?.experienceText || "--",
        address: this.jobListName[0]?.address || "--",
        tags: this.jobListName[0]?.tags || [],
        district1: this.jobListName[0]?.district1 || "--",
        district2: this.jobListName[0]?.district2 || "--",
        district3: this.jobListName[0]?.district3 || "--",
        content: this.jobListName[0]?.content || "--",
        nature: this.jobListName[0]?.nature || "--",
        natureText: natureMap[this.jobListName[0]?.nature] || "--",
      };
    },
  },
  data() {
    return {
      ids: [],
      auditSelectStatus: "",
      multipleSelection: [],
      downloadLoading: false,
      value: true,
      examineDialog: false,
      examineOneDialog: false,
      allExamineDialog: false,
      audit: 1,
      id: "",
      auditQuery: [
        {
          id: "",
          audit: 1,
          reason: "",
        },
      ],
      // 职位列表
      jobLists: {
        page: 1,
        pageSize: 10,
        audit: "",
        display: "",
        keyType: null,
        keyword: "",
        listType: "",
        sort: "",
      },
      total: "",
      jobListArray: [],
      jobListName: [],
      auditStatus: [
        { value: "", name: "不限审核状态" },
        { value: 0, name: "待审核" },
        { value: 1, name: "已通过" },
        { value: 2, name: "未通过" },
      ],
      hireStatus: [
        { value: "", name: "不限招聘状态" },
        { value: 0, name: "已暂停" },
        { value: 1, name: "招聘中" },
      ],
      addTimeSort: [
        { value: "", name: "按添加时间排序" },
        { value: "refreshTime", name: "按刷新时间排序" },
        { value: "updateTime", name: "按修改时间排序" },
      ],
      positionName: [
        { value: 1, name: "职位名称" },
        { value: 2, name: "公司名称" },
        { value: 3, name: "职位ID" },
        { value: 4, name: "公司ID" },
        { value: 5, name: "会员ID" },
        { value: 6, name: "会员手机号" },
      ],
      selectedRows: [],
      styleOneDialog: false,
      jobNameDialog: false,
      // 地区列表
      areaList: [],
      // 公司弹框
      companyNameDialog: false,
      // 公司名称
      companyNames: {},
    };
  },
  created() {
    this.jobList();
    this.selCategoryDistrictList();
    if (this.$route.query) {
      console.log(this.$route.query);
      this.jobLists.audit = this.$route.query.audit;
    }
  },
  methods: {
    async selCategoryDistrictList() {
      try {
        const res = await selCategoryDistrictListApi();
        this.areaList = res.data[0].map((item) => ({
          label: item.name, // 父级项的 value 设置为 name
          value: item.id,
          children: item.children
            ? item.children.map((child) => ({
                label: child.name, // 子项的 label 设置为 name
                value: child.id, // 子项的 value 设置为 id 的字符串形式
                children: child.children.map((subDistrict) => ({
                  label: subDistrict.name, // 父级项的 value 设置为 name
                  value: subDistrict.id,
                })), // 子项的 children 默认为空数组，如果需要更深层次的数据结构，可以在这里添加逻辑
              }))
            : [], // 如果没有 categoryDistricts，children 设置为空数组
        }));
        console.log(this.areaList);
      } catch (error) {
        console.error("获取地区列表失败:", error);
      }
    },
    // 职位名称
    jobClick(row) {
      this.jobNameDialog = true;
      this.jobListName = [row];
      console.log(this.jobListName);
    },
    // 单个审核确认
    async auditOneClick() {
      if (this.auditQuery[0].audit === 2 && !this.auditQuery[0].reason) {
        this.$message.error("请填写未通过原因");
        return;
      }
      const res = await updateAuditApi(this.auditQuery);
      console.log(res);
      if (res.code === 1) {
        this.$message.success("设置成功!");
        this.examineOneDialog = false;
        this.jobList();
      } else {
        this.$message.error("设置失败");
      }
    },
    // 点击公司名称
    companyClick(row) {
      this.companyNameDialog = true;
      this.companyNames = row;
    },
    // 批量删除
    delBtnClick() {
      if (this.ids.length === 0) {
        this.$message.warning("请先选择要删除的职位");
        return;
      }
      this.$confirm("此操作将永久删除该职位, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delPositionByIdsApi(this.ids);
          if (res.code === 1) {
            this.$message.success("删除成功!");
            this.jobList();
            this.ids = [];
          } else {
            this.$message.error("删除失败");
          }
        })
        .catch(() => {});
    },
    // 点击职位管理
    async manageClick(uid) {
      console.log(uid);
      const res = await selTokenByUIdApi(uid);
      console.log(res);
      window.location.href = `http://localhost:8889/#/member_homepage?uid=${res.data.id}&token=${res.data.token}&mid=${res.data.mid}`;
      // window.location.href = res.data.jumpUrl.split('?')[0]
      console.log(res.data.jumpUrl.split("?")[0]);
    },
    // 选择排序状态的时候
    handleSortChange(value) {
      console.log(value);
      this.jobLists.page = 1;
      this.jobList();
    },
    // 选择招聘状态的时候
    handleSelectStatusChange(value) {
      console.log(value);
      this.jobLists.page = 1;
      this.jobList();
    },
    // 选择审核状态的时候
    handleSelectAuditChange(value) {
      console.log(value);
      this.jobLists.page = 1;
      this.jobList();
    },
    // 点击提交
    searchClick() {
      this.jobList();
    },
    delBtn(id) {
      this.ids.push(id);
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delPositionByIdsApi(this.ids);
          if (res.code === 1) {
            this.$message.success("删除成功!");
            this.jobList();
            this.ids = [];
          } else {
            this.$message.error("删除失败");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    batchDelBtn() {
      this.$confirm("此操作将永久删除选中的职位, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSelectionChange(selection) {
      try {
        this.selectedRows = selection.map((item) => ({
          id: item.id,
          audit: item.audit || 0, // 使用相同的默认值
          reason: item.reason || "", // 使用相同的默认值
        }));
        this.ids = this.selectedRows.map((item) => item.id);
        console.log(this.selectedRows);
      } catch (error) {
        console.error("选择状态更新失败:", error);
      }
    },
    // 编辑职位
    editBtn(row) {
      console.log(row);
      this.$router.push({
        name: "editPosition",
        params: {
          row,
        },
      });
      localStorage.setItem("editPosition", JSON.stringify(row));
    },
    async jobList() {
      const res = await jobListApi(this.jobLists);
      console.log(res);
      this.jobListArray = res.records.map((item) => ({
        ...item,
        userStatus: item.userStatus === 1,
      }));
      this.total = res.total;
      console.log(this.jobListArray);
    },
    // 职位状态
    async switchChange(row) {
      // const res = await updateDisplayByIdApi(row);
      // console.log(res);
      row.display = row.display ? 1 : 0;
      this.$confirm(
        "确定要把测试的招聘状态设为暂停招聘吗？ 设为暂停招聘后此职位将无法被用户搜索?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          try {
            const res = await updateDisplayByIdApi({
              display: row.display,
              id: row.id,
            });
            console.log(res);
            if (res.code === 1) {
              this.$message.success("修改成功!");
              this.jobList();
            } else {
              this.$message.error("修改失败");
            }
          } catch {
            this.$message.error("修改失败");
          }
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "已取消",
          // });
          this.jobList();
        });
    },
    // 审核状态
    async auditClick() {
      try {
        // 如果是未通过状态但没有填写原因
        if (this.selectedRows[0].audit === 2 && !this.selectedRows[0].reason) {
          this.$message.error("请填写未通过原因");
          return;
        }
        // 获取第一项的 audit 和 reason
        const { audit, reason } = this.selectedRows[0];
        // 同步所有选中项的 audit 和 reason
        this.selectedRows = this.selectedRows.map((row) => ({
          ...row,
          audit, // 使用第一项的 audit
          reason, // 使用第一项的 reason
        }));
        const res = await updateAuditApi(this.selectedRows);
        console.log(res);
        if (res.code === 1) {
          this.$message.success("设置成功!");
          this.examineDialog = false;
          this.jobList();
          this.$refs.multipleTable.clearSelection();
        } else {
          this.$message.error("设置失败");
        }
      } catch {
        // this.$message.error("设置失败");
      }
    },
    // 审核职位
    examineClick(id) {
      console.log(id);
      this.auditQuery[0].id = id;
      console.log(this.auditQuery);
      this.examineOneDialog = true;
    },
    // 批量审核
    examinePlClick() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请先选择要审核的职位");
        return;
      }
      this.examineDialog = true;
    },
    // 点击分页
    handleSizeChange(value) {
      this.jobLists.pageSize = value;
      this.jobList();
    },
    // 点击分页
    handleCurrentChange(value) {
      this.jobLists.page = value;
      this.jobList();
    },
    getDistrictText(district1, district2, district3) {
      let text = "";

      // 查找省级
      const province = this.areaList.find((item) => item.value === district1);
      if (province) {
        text += province.label;

        // 查找市级
        const city = province.children?.find(
          (item) => item.value === district2
        );
        if (city) {
          text += " / " + city.label;

          // 查找区级
          const area = city.children?.find((item) => item.value === district3);
          if (area) {
            text += " / " + area.label;
          }
        }
      }

      return text || "--";
    },
  },
};
</script>

<style scoped>
.tags-container {
  padding: 4px 11px;
  background-color: #f5f7fa;
  border-radius: 4px;
  min-height: 32px;
  border: 1px solid #dcdfe6;
}
</style>
